
import UIKit
import GradientLoadingBar
import Alamofire
import Reachability


class AssistantTabViewController: UIViewController {
    var myNavigationController: UINavigationController?
    var currentPage = 1
    var total = 0
    var pageTitle = "助手"
    var isFavorite = false
    var tabList: [String] = []
    var assistantSectionList: [AssistantSection] = []
    var list:[Assistant] = []
    let reachability = try! Reachability()
    // 懒加载
    var  tabPageViewController: TabPageViewController!
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
           return [NSAttributedString.Key.foregroundColor: UIColor.white]
       }
  
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = pageTitle
        
        tabPageViewController = TabPageViewController()
        getLocalJson()
        self.view.backgroundColor = primaryBackgroundColor
        reachability.whenReachable = { reachability in
            if reachability.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
            self.getAssistantList()
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
        
    }
    
    func getLocalJson(){
        let data = Data(StoreManager.getAssistantJson().utf8)
        do {
            let jsonDecoder = JSONDecoder()
            let assistantResponse = try jsonDecoder.decode(AssistantResponse.self, from: data)
            
            let list = assistantResponse.data
            
            parseSection(list: list)
        } catch {
            print("getLocalJson:\(error)")
        }
    }
    
    func getAssistantList(){
        let parameters = BasicPageParameters(page: currentPage)
        AFManager.sharedInstance.manager.request("\(baseUrl)personal_helper/listV2",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            if let string = response.value{
                print("getAssistantList=\(string)")
                let data = Data(string.utf8)
                do {
                    let jsonDecoder = JSONDecoder()
                    let assistantListResponse = try jsonDecoder.decode(AssistantListResponse.self, from: data)
                    
                    let isLastPage = assistantListResponse.data.isLastPage
                    print("isLastPage=\(isLastPage)")
                    self.list = self.list + assistantListResponse.data.list
                    self.total = assistantListResponse.data.total
                    self.currentPage = self.currentPage + 1
                    if !isLastPage{
                        self.getAssistantList()
                    }else{
                        self.parseSection(list: self.list)
                        if  !self.list.isEmpty , self.list.count == self.total{
                            //save to local
                            do {
                                let assistantResponse = AssistantResponse(code: 200, data: self.list, message: "success")
                                let jsonEncoder = JSONEncoder()
                                let jsonData = try jsonEncoder.encode(assistantResponse)
                                let json = String(data: jsonData, encoding: String.Encoding.utf8)
                                if let jsonString = json{
                                    StoreManager.setAssistantJson(json: jsonString)
                                }
                            } catch {
                                print(error)
                            }
                        }
                    }
                    
                } catch {
                    print(error)
                }
            }
        }
        
    }
    
    func parseSection(list:[Assistant]){
        
        var assistantAssistant: Assistant?
        var index = -1
        self.assistantSectionList = []
        self.tabList = []
        for assistant in list{
            if assistantAssistant == nil || assistant.category != assistantAssistant?.category{
                index = index + 1
                var assistantSection = AssistantSection(data: [])
                assistantSection.title = assistant.category
                self.tabList.append(assistant.category)
                self.assistantSectionList.append(assistantSection)
                assistantAssistant = assistant
            }
            
            self.assistantSectionList[index].data.append(assistant)
           
        }
        if tabPageViewController.tabItems.isEmpty{
            var index = 0
            tabPageViewController.isInfinity = false
            tabPageViewController.option.currentColor = .primaryColor
            tabPageViewController.option.defaultColor = .white
            tabPageViewController.option.pageBackgoundColor = primaryDarkBackgroundColor
            tabPageViewController.option.tabBackgroundColor = primaryBackgroundColor
            tabPageViewController.option.tabMargin = 16.0
            tabPageViewController.option.fontSize = 16.2

            
           
            for assistantSection in assistantSectionList{
                let vc = AssistantViewController()
                
                
                if myNavigationController != nil{
                    vc.myNavigationController = myNavigationController
                }else{
                    vc.myNavigationController = self.navigationController
                }
                
                vc.list = assistantSectionList[index].data;
                tabPageViewController.tabItems.append((vc,assistantSection.title))
                index += 1
            }
            self.view.addSubview(tabPageViewController.view)
            tabPageViewController.view.snp.makeConstraints { make in
                make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
                make.width.equalTo(self.view)
            }
        }
    }
    
}

